package edu.sdjzu.exam.mapper;

import edu.sdjzu.exam.domain.auth.Role;
import edu.sdjzu.exam.domain.auth.UserRole;
import edu.sdjzu.exam.domain.auth.Permission;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserRoleMapper {
    @Insert("INSERT INTO User_Roles (user_id, role_id) VALUES (#{userId}, #{roleId})")
    @Options(useGeneratedKeys = true, keyProperty = "userRoleId")
    void insert(UserRole userRole);

    @Delete("DELETE FROM User_Roles WHERE user_id = #{userId} AND role_id = #{roleId}")
    void delete(Long userId, Long roleId);

    @Select("SELECT r.* FROM Roles r JOIN User_Roles ur ON r.role_id = ur.role_id WHERE ur.user_id = #{userId}")
    List<Role> findRolesByUserId(Long userId);

    @Select("SELECT p.* FROM Permissions p " +
            "JOIN Role_Permissions rp ON p.permission_id = rp.permission_id " +
            "JOIN User_Roles ur ON rp.role_id = ur.role_id " +
            "WHERE ur.user_id = #{userId}")
    List<Permission> findPermissionsByUserId(Long userId);

    @Select("SELECT COUNT(*) > 0 FROM User_Roles ur " +
            "JOIN Role_Permissions rp ON ur.role_id = rp.role_id " +
            "JOIN Permissions p ON rp.permission_id = p.permission_id " +
            "WHERE ur.user_id = #{userId} AND p.permission_name = #{permissionName}")
    boolean hasPermission(@Param("userId") Long userId, @Param("permissionName") String permissionName);
    
    @Select("SELECT u.* FROM Users u JOIN User_Roles ur ON u.user_id = ur.user_id WHERE ur.role_id = #{roleId}")
    List<edu.sdjzu.exam.domain.auth.User> findUsersByRoleId(Long roleId);
}
